package com.e3.core.base;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ServiceLocator {
	
	private static ApplicationContext context;
	
	private static boolean isInited = false;
	
	public static <T> T getQueryService(Class<T> clazz){
		return getServiceBean(clazz);
	}
	
	public static <T> T getService(Class<T> clazz){
		String serviceName = clazz.getSimpleName();
		return getService(serviceName,clazz);
	}
	
	public static <T> T getQueryService(String name,Class<T> clazz){
		return getServiceBean(clazz);
	}
	
	public static <T> T getService(String name,Class<T> clazz){
//		T bean = getServiceBean(clazz);
//		return (T)Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz}, new ServiceInvoker(bean));
		return getServiceBean(name, clazz);
	}
	
	private static <T> T getServiceBean(Class<T> clazz){
		String serviceName = clazz.getSimpleName();
		return getServiceBean(serviceName,clazz);
	}
	
	@SuppressWarnings("unchecked")
	private static <T> T getServiceBean(String name,Class<T> clazz){
		if(!isInited){
			init();
		}
		return (T)context.getBean(name);
	}
	
	public synchronized static void init(){
		if(isInited){
			return;
		}
		context = new ClassPathXmlApplicationContext(new String[]{"conf/spring-context.xml"});
		isInited = true;
	}
}
